package com.xxd.gulimail.ware.service.impl;

import com.xxd.common.utils.R;
import com.xxd.gulimail.ware.feign.ProductFeignService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxd.common.utils.PageUtils;
import com.xxd.common.utils.Query;

import com.xxd.gulimail.ware.dao.WareSkuDao;
import com.xxd.gulimail.ware.entity.WareSkuEntity;
import com.xxd.gulimail.ware.service.WareSkuService;

import javax.annotation.Resource;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Resource
    private WareSkuDao wareSkuDao;
    @Resource
    private ProductFeignService productFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        skuId:
//        wareId:
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuid = (String) params.get("skuId");
        if (StringUtils.isNotEmpty(skuid)){
            wrapper.eq("sku_id",skuid);
        }
        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStoke(Long skuId, Long wareId, Integer skuNum) {
        //1.若没有则新增，有则修改
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities.size()>0){
            wareSkuDao.addStoke(skuId,wareId,skuNum);
        }else{
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO远程查询sku的名字,为了此处报异常不回滚，使用try..catch先抛出
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0){
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }

            wareSkuDao.insert(wareSkuEntity);
        }

    }

}